/*
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-11-07 12:14:27
 * @LastEditTime : 2024-02-26 14:19:15
 */
import { Body, Headers, Inject, Post } from '@midwayjs/decorator';
import { CoolController, BaseController, RESCODE } from '@cool-midway/core';
import axios from 'axios';

/**
 * 代理
 */
@CoolController()
export class ProxyController extends BaseController {
  static dashToCamelCase(obj) {
    const newObj = {};

    // 遍历对象的所有键值对
    for (let key in obj) {
      // 将key从'content-type'转换为'contentType'
      let camelKey = key.replace(/-([a-z])/g, (m, w) => {
        return w.toUpperCase();
      });

      // 将原对象中的值复制到新对象，并使用驼峰式命名的键
      newObj[camelKey] = obj[key];
    }

    return newObj;
  }

  @Post('/')
  async proxy(@Body() body) {
    // 或者如果你想要修改全局默认配置
    // axios.defaults.xsrfCookieName = undefined;
    axios.defaults.xsrfHeaderName = undefined;

    // 如果你正在处理withCredentials，也可以将其设置为false以避免发送cookies（包括可能用于XSRF防护的cookie）
    // axios.defaults.withCredentials = false;
    const { headers } = this.baseCtx;
    /**
     * @description: 将headers中所有以‘-’连接的替换为驼峰式
     * @return {*}
     */
    const proxyHeaders = ProxyController.dashToCamelCase(headers);
    try {
      const proxyBody = {
        ...body,
      };
      delete proxyBody.ik_datav_proxy_api;
      delete proxyBody.ik_datav_proxy_method;
      const config = {
        method: body.ik_datav_proxy_method,
        url: body.ik_datav_proxy_api,
        timeout: body.ik_datav_proxy_timeout || 10000,
        maxContentLength: Infinity,
        maxBodyLength: Infinity,
        headers: proxyHeaders,
        data: proxyBody || {},
      };
      const response = await axios(config);
      return response.data;
    } catch (error) {
      return this.ok({
        code: RESCODE.COMMFAIL,
        message: error?.message || '请求错误',
      });
    }
  }
}
